<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="obj.name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="obj.age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model.number="obj.sex">
        <option value="1">男</option>
        <option value="0">女</option>
      </select>
    </div>
    <div>
      <button @click="confirm(obj.id)">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in list" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex === 0 ? "女" : "男" }}</td>
          <td>
            <button @click="remove(item.id)">删除</button>
            <button @click="edit(item)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        { id: 1, name: "tom", age: "18", sex: 1 },
        { id: 2, name: "jone", age: "17", sex: 0 },
      ],
      obj: { id: null, name: "", age: "", sex: 0 },
    };
  },
  computed: {},
  methods: {
    confirm(id) {
      if (id === null) {
        // 判断是否输入了内容
        if (this.obj.name === "" || this.obj.age === "")
          return alert("请输入完整得信息");
        // 判断序号
        this.list
          ? (this.obj.id = this.list[this.list.length - 1].id + 1)
          : (this.obj.id = 1);
        // 添加数据
        this.list.push({ ...this.obj });
        // 设置为默认表单数据
        this.obj = { id: null, name: "", age: "", sex: 0 };
      } else {
        // 选择修改的数据
        const index = this.list.findIndex((item) => item.id === id);
        // 修改
        this.list[index] = { ...this.obj };
        // 重置
        this.obj = { id: null, name: "", age: "", sex: 0 };
      }
    },
    remove(id) {
      this.list.splice(id - 1, 1);
    },
    edit(data) {
      this.obj = { ...data };
    },
  },
};
</script>
